const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");

const Point = function(x, y) {
    this.x = x;
    this.y = y;
};

const Polygon = function(
    centerX,
    centerY,
    radius,
    sides,
    startAngle,
    strokeStyle,
    fillStyle,
    filled
) {
    this.x = centerX;
    this.y = centerY;
    this.radius = radius;
    this.sides = sides;
    this.startAngle = startAngle;
    this.strokeStyle = strokeStyle;
    this.fillStyle = fillStyle;
    this.filled = filled;
};

Polygon.prototype = {
    getPoints: function() {
        let points = [],
            angle = this.startAngle || 0;
        for (let i = 0; i < this.sides; ++i) {
            points.push(
                new Point(
                    this.x + this.radius * Math.sin(angle),
                    this.y - this.radius * Math.cos(angle)
                )
            );
            angle += (2 * Math.PI) / this.sides;
        }
        return points;
    },
    createPath: function(context) {
        const points = this.getPoints();
        context.beginPath();
        context.moveTo(points[0].x, points[0].y);
        for (let i = 1; i < this.sides; ++i) {
            context.lineTo(points[i].x, points[i].y);
        }
        context.closePath();
    },
    stroke: function(context) {
        context.save();
        this.createPath(context);
        context.strokeStyle = this.strokeStyle;
        context.stroke();
        context.restore();
    },
    fill: function() {
        context.save();
        this.createPath(context);
        context.fillStyle = this.fillStyle;
        context.fill();
        context.restore();
    },
    move: function(x, y) {
        this.x = x;
        this.y = y;
    }
};

const shape1 = new Polygon(100, 100, 100, 3, 0, "#000000", "rgba(0, 0, 0, .5)", true);
const shape2 = new Polygon(300, 100, 100, 4, 0, "orange", "", true);
const shape3 = new Polygon(500, 100, 100, 5, 0, "orange", "rgba(255, 255, 0,.8)", true);
shape1.fill(context);
shape2.stroke(context);
shape3.fill(context);
